    //
//  UserProfile.m
//  SpendFunk
//
//  Created by AnhLH-Oriolus on 11/26/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "UserProfile.h"
#import "Global.h"


#define kUserID     @"userid"
#define kUserName   @"username"
#define kPassword	@"password"
#define kFirstName	@"firstname"
#define kLastName	@"lastname"
#define kEmail		@"email"
#define kAvatar		@"avatar"
#define kUserType	@"user_type"
#define kFacebookID	@"facebook_id"
#define kTwitterID	@"twitter_id"

@implementation UserProfile


// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
	[super loadView];
}

-(void)getUserProfile
{
	if(!g_dictInfoUserSpendFunk)
		g_dictInfoUserSpendFunk = [[NSMutableDictionary alloc] init];
	
	isUpdate = FALSE;
	NSString *post = [NSString stringWithFormat:@"userid=%@", g_strLoginUserId];
	NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];  
	NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
	
	NSLog(@"%@",post);
	NSURL *url = [NSURL URLWithString:@"http://demo.thejupitech.com/snt/spendfunk/api/users/getprofilebyuserid"];
	NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
	[theRequest setHTTPMethod:@"POST"];  
	[theRequest setValue:postLength forHTTPHeaderField:@"Content-Length"];  
	[theRequest setHTTPBody:postData];	
	
	NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
	if( theConnection )
	{
		m_pWebData = [[NSMutableData data] retain];
	}
	else
	{
		
	}
	
	timer= [NSTimer timerWithTimeInterval:0.3 target:nil selector:@selector(checkUpdate) userInfo:nil repeats:YES];
}

-(void)checkUpdate{
	if(isUpdate){
		[self updateUserProfile];
		[timer invalidate];
	}
	NSLog(@"dang xy ly nhe.");
}


-(void)updateUserProfile
{	
	/*
	NSString *post = [[NSString alloc] initWithFormat:@"userid=%@&email=%@&firstname=%@&lastname=%@&avatar=%@&facebook_id=%@&twitter_id=%@&",
					  g_strLoginUserId,
					  [g_dictInfoUserSpendFunk objectForKey:kEmail],
					  [g_dictInfoUserSpendFunk objectForKey:kFirstName],
					  [g_dictInfoUserSpendFunk objectForKey:kLastName],
					  [g_dictInfoUserSpendFunk objectForKey:kAvatar],
					  //[g_dictInfoUserSpendFunk objectForKey:kFacebookID],
					  g_strFacebookId,
					  [g_dictInfoUserSpendFunk objectForKey:kTwitterID]];
	 */
	NSString *post = [[NSString alloc] initWithFormat:@"userid=%@&email=%@&firstname=%@&lastname=%@&avatar=%@&facebook_id=%@&twitter_id=%@&",
					  g_strLoginUserId,
					  @"dongmh.dce.hut@gmail.com",
					  @"dong",
					  @"mm",
					  @"af.jpg",
					  //[g_dictInfoUserSpendFunk objectForKey:kFacebookID],
					  g_strFacebookId,
					  [g_dictInfoUserSpendFunk objectForKey:kTwitterID]];
	NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];  
	NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];  
	NSLog(@"%@",post);
	NSURL *url = [NSURL URLWithString:@"http://demo.thejupitech.com/snt/spendfunk/api/users/updateprofilebyuserid"];
	NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
	[theRequest setHTTPMethod:@"POST"];  
	[theRequest setValue:postLength forHTTPHeaderField:@"Content-Length"];  
	[theRequest setHTTPBody:postData];	
	
	NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
	if( theConnection )
	{
		m_pWebData = [[NSMutableData data] retain];
	}
	else
	{
		
	}
}


#pragma mark delegate connection
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
	[m_pWebData setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
	[m_pWebData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
	UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Cannot connect to internet" message:@"Please connect to internet!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
	[alert show];
	
	[alert release];
	[connection release];
	[m_pWebData release];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
	NSData *loginStatus = [[NSData alloc] initWithBytes: [m_pWebData mutableBytes] length:[m_pWebData length]];
	
	NSString *a = [[NSString alloc] initWithData:loginStatus encoding:NSUTF8StringEncoding];
	NSLog(@"%@",a);
	
	NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithData:loginStatus];
	[xmlParser setDelegate:self];
	
	BOOL success = [xmlParser parse];
	
	if(success)
	{
		NSLog(@"No Errors");
		if(!g_dictInfoUserSpendFunk){
			g_dictInfoUserSpendFunk = [[NSMutableDictionary alloc] init];
		}
	}
	else
	{
		NSLog(@"Error Error Error!!!");
	}
	
	[connection release];
	[m_pWebData release];
}

#pragma mark delegate xmlParser
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName 
  namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName 
	attributes:(NSDictionary *)attributeDict {
	if(!currentElement) 
		currentElement = [[NSString alloc] initWithString:elementName];
	else
		currentElement = [elementName retain];
	
	NSLog(@"Processing Element: %@", elementName);
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
	NSLog(@"Processing Value: %@", string);
	
	if([currentElement isEqualToString:kUserID]){
		[g_dictInfoUserSpendFunk setObject:string forKey:kUserID];
	}
	if([currentElement isEqualToString:kUserName]){
		[g_dictInfoUserSpendFunk setObject:string forKey:kUserName];
	}
	if([currentElement isEqualToString:kPassword]){
		[g_dictInfoUserSpendFunk setObject:string forKey:kPassword];
	}
	if([currentElement isEqualToString:kFirstName]){
		[g_dictInfoUserSpendFunk setObject:string forKey:kFirstName];
	}
	if([currentElement isEqualToString:kLastName]){
		[g_dictInfoUserSpendFunk setObject:string forKey:kLastName];
	}
	if([currentElement isEqualToString:kEmail]){
		[g_dictInfoUserSpendFunk setObject:string forKey:kEmail];
	}
	if([currentElement isEqualToString:kAvatar]){
		[g_dictInfoUserSpendFunk setObject:string forKey:kAvatar];
	}
	if([currentElement isEqualToString:kUserType]){
		[g_dictInfoUserSpendFunk setObject:string forKey:kUserType];
	}
	if([currentElement isEqualToString:kFacebookID]){
		[g_dictInfoUserSpendFunk setObject:string forKey:kFacebookID];
	}
	if([currentElement isEqualToString:kTwitterID]){
		[g_dictInfoUserSpendFunk setObject:string forKey:kTwitterID];
	}
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName 
  namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
	
	if([elementName isEqualToString:@"xml"] && isUpdate == FALSE){
		isUpdate = TRUE;
		[self updateUserProfile];
	}
	[currentElement release];
	currentElement = nil;
	[currentElementValue release];
	currentElementValue = nil;
}

/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
}
*/

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations.
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
}


@end
